import { createSlice } from '@reduxjs/toolkit'

interface ThemeState {
  isDark: boolean
}

// 从本地存储读取主题设置，如果没有则默认为浅色主题
const getInitialTheme = (): boolean => {
  try {
    const savedTheme = localStorage.getItem('theme')
    if (savedTheme === null) return false
    return JSON.parse(savedTheme)
  } catch (error) {
    // 如果解析失败，清除无效数据并返回默认值
    console.log(error)
    localStorage.removeItem('theme')
    return false
  }
}

const initialState: ThemeState = {
  isDark: getInitialTheme()
}

const themeSlice = createSlice({
  name: 'theme',
  initialState,
  reducers: {
    toggleTheme: (state) => {
      state.isDark = !state.isDark
      // 保存到本地存储
      localStorage.setItem('theme', JSON.stringify(state.isDark))
    },
    setTheme: (state, action) => {
      state.isDark = action.payload
      // 保存到本地存储
      localStorage.setItem('theme', JSON.stringify(state.isDark))
    }
  }
})

export const { toggleTheme, setTheme } = themeSlice.actions
export default themeSlice.reducer
